package com.dy.yunying.biz.utils;

import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;
import net.sf.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.baomidou.mybatisplus.core.toolkit.StringUtils.underlineToCamel;

/**
 * @author cx
 * @version 1.0.0
 * @ClassName MapUtils.java
 * @createTime 2021年06月10日 11:24:00
 */
public class MapUtils {
	/**
	 * 将对象装换为map
	 *
	 * @param bean
	 * @return
	 */
	public static <T> Map<String, Object> beanToMap(T bean) {
		Map<String, Object> map = Maps.newHashMap();
		if (bean != null) {
			BeanMap beanMap = BeanMap.create(bean);
			for (Object key : beanMap.keySet()) {
				map.put(key + "", beanMap.get(key));
			}
		}
		return map;
	}

	/**
	 * 将map装换为javabean对象
	 *
	 * @param map
	 * @param bean
	 * @return
	 */
	public static <T> T mapToBean(Map<String, Object> map, T bean) {
		BeanMap beanMap = BeanMap.create(bean);
		beanMap.putAll(map);
		return bean;
	}

	/**
	 * 将List<T>转换为List<Map<String, Object>>
	 *
	 * @param objList
	 * @return
	 */
	public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
		List<Map<String, Object>> list = Lists.newArrayList();
		if (objList != null && objList.size() > 0) {
			Map<String, Object> map = null;
			T bean = null;
			for (int i = 0, size = objList.size(); i < size; i++) {
				bean = objList.get(i);
				map = beanToMap(bean);
				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 将List<Map<String,Object>>转换为List<T>
	 *
	 * @param maps
	 * @param clazz
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps, Class<T> clazz)
			throws InstantiationException, IllegalAccessException {
		List<T> list = Lists.newArrayList();
		if (maps != null && maps.size() > 0) {
			Map<String, Object> map = null;
			T bean = null;
			for (int i = 0, size = maps.size(); i < size; i++) {
				map = maps.get(i);
				bean = clazz.newInstance();
				mapToBean(map, bean);
				list.add(bean);
			}
		}
		return list;
	}



	/**
	 * 将map对于的key转换为驼峰格式
	 * @param map
	 * @return
	 */

	public static Map<String, Object> toReplaceKeyLow(Map<String, Object> map) {
		Map reMap = new HashMap();

		if (map != null) {
			Iterator var2 = map.entrySet().iterator();

			while (var2.hasNext()) {
				Map.Entry<String, Object> entry = (Map.Entry) var2.next();
				reMap.put(underlineToCamel((String) entry.getKey()), map.get(entry.getKey()));
			}

			map.clear();
		}

		return reMap;
	}


}
